package me.zhangyifeng.blog.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import me.zhangyifeng.blog.model.domain.User;
import me.zhangyifeng.blog.model.dto.MaydayConst;

/**
 * 普通用户拦截器，用于拦截用户中心的请求
 */
@WebFilter(filterName = "userFilter", urlPatterns = {"/user/*"})
public class UserFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String uri = httpRequest.getRequestURI();
        
        // 登录和注册页面不需要拦截
        if (uri.contains("/user/login") || uri.contains("/user/register")) {
            chain.doFilter(request, response);
            return;
        }
        
        // 获取session，判断用户是否已登录
        HttpSession session = httpRequest.getSession();
        User user = (User) session.getAttribute(MaydayConst.USER_SESSION_KEY);
        if (user == null) {
            httpResponse.sendRedirect("/user/login");
            return;
        }
        
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}
